import React, { Component, createRef } from 'react';
import { Card, Button, Form, Input, DatePicker, message, Spin } from 'antd';
import moment from 'moment';
import E from 'wangeditor';
import './edit.less';
import { getArticleById, saveArticle } from '../../requests';
import { SetData } from '../commom';
@Form.create()
class ArticalEdit extends Component {
  constructor() {
    super();
    this.editor = null;
    this.divRef = createRef();
    this.state = {
      id: null,
      isLoading: true
    };
  }
  handleSubmit = e => {
    this.setState({
      isLoading: true
    });
    //通过事件对象来获取值
    e.preventDefault();
    //检验
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values.createAt = moment(values.createAt).valueOf();
        saveArticle(this.props.match.params.id, values)
          .then(res => {
            if (res.code === 200) {
              message.success(res.data.msg);
            }
          })
          .finally(() => {
            SetData.bind(this, {
              isLoading: false
            });
          });
      }
    });
  };
  componentDidMount() {
    this.setState({
      isLoading: true
    });
    this.editor = new E(this.divRef.current);
    this.editor.customConfig.onchange = html => {
      this.props.form.setFieldsValue({
        content: html
      });
    };
    this.editor.create(); //注意create这行代码要放在最后面
    this.getArticleDetail();
  }
  getArticleDetail = () => {
    getArticleById(this.props.match.params.id)
      .then(res => {
        if (res.code === 200) {
          const { id, ...data } = res.data;
          SetData.bind(this, {
            id
          });
          data.createAt = moment(data.createAt);
          this.props.form.setFieldsValue(data);
          this.editor.txt.html(data.content);
        }
      })
      .finally(() => {
        SetData.bind(this, {
          isLoading: false
        });
      });
  };
  render() {
    const formItemLayout = {
      labelCol: {
        //label的布局，默认是右对齐的
        span: 2
      },
      wrapperCol: {
        span: 18
      }
    };
    const { getFieldDecorator } = this.props.form; //只要使用了高阶组件Form.create()，才可以使用这个this.props
    return (
      //这个方法是可行的啊
      // <Card title={this.props.location.state.title} extra={<Button>返回</Button>}>
      //   编辑内容
      // </Card>
      <Spin spinning={this.state.isLoading}>
        <Card
          title={this.props.location.state.title}
          extra={<Button onClick={this.props.history.goBack}>返回</Button>}
        >
          <Form onSubmit={this.handleSubmit}>
            <Form.Item label="标题" {...formItemLayout}>
              {getFieldDecorator('title', {
                //这个username是我们要提交的字段名
                rules: [
                  //rules是数字（必须），里面的元素是对象
                  {
                    required: true,
                    message: '该项必填'
                  }
                ]
              })(<Input placeholder="标题" />)}
            </Form.Item>
            <Form.Item label="作者" {...formItemLayout}>
              {getFieldDecorator('author', {
                rules: [
                  {
                    required: true,
                    message: '该项必填'
                  }
                ]
              })(<Input placeholder="admin" />)}
            </Form.Item>
            <Form.Item label="阅读量" {...formItemLayout}>
              {getFieldDecorator('amount', {
                rules: [
                  {
                    required: true,
                    message: '该项必填'
                  },
                  {
                    pattern: /^[0-9]*$/,
                    message: '该项必须填数字'
                  }
                ]
              })(<Input placeholder="0" />)}
            </Form.Item>
            <Form.Item label="发布时间" {...formItemLayout}>
              {getFieldDecorator('createAt', {
                rules: [
                  {
                    required: true,
                    message: '该项必填'
                  }
                ]
              })(<DatePicker showTime placeholder="选择时间" />)}
            </Form.Item>
            <Form.Item label="内容" {...formItemLayout}>
              {getFieldDecorator('content', {
                rules: [
                  {
                    required: true,
                    message: '该项必填'
                  }
                ]
              })(<div className="editor" ref={this.divRef}></div>)}
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 2 }}>
              <Button
                type="primary"
                htmlType="submit"
                className="login-form-button"
              >
                保存
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </Spin>
    );
  }
}
export default ArticalEdit;
